package cn.coastalinfo.project.drools.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import cn.coastalinfo.project.drools.fact.RuleFact;
import cn.coastalinfo.project.drools.service.RuleEngineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.coastalinfo.framework.aspectj.lang.annotation.Log;
import cn.coastalinfo.framework.aspectj.lang.enums.BusinessType;
import cn.coastalinfo.project.drools.domain.vo.RuleVo;
import cn.coastalinfo.project.drools.domain.bo.RuleBo;
import cn.coastalinfo.project.drools.service.IRuleService;
import cn.coastalinfo.framework.web.controller.BaseController;
import cn.coastalinfo.framework.web.domain.AjaxResult;
import cn.coastalinfo.common.utils.poi.ExcelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;


import cn.coastalinfo.framework.web.page.TableDataInfo;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
 * 规则Controller
 * 
 * @author hadge
 * @date 2024-06-07
 */
@Api("规则管理")
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/drools/rule")
public class RuleController extends BaseController
{
    @Autowired
    private IRuleService ruleService;

    @Autowired
    private RuleEngineService ruleEngineService;

    /**
     * 查询规则列表
     */
    @ApiOperation("获取规则列表")
    //@PreAuthorize("@ss.hasPermi('drools:rule:list')")
    @GetMapping("/list")
    public TableDataInfo list(RuleBo ruleBo)
    {
        startPage();
        List<RuleVo> list = ruleService.queryList(ruleBo);
        return getDataTable(list);
    }

    /**
     * 导出规则列表
     */
    //@PreAuthorize("@ss.hasPermi('drools:rule:export')")
    @Log(title = "规则", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RuleBo ruleBo)
    {
        List<RuleVo> list = ruleService.queryList(ruleBo);
        ExcelUtil<RuleVo> util = new ExcelUtil<RuleVo>(RuleVo.class);
        util.exportExcel(response, list, "规则数据");
    }

    /**
     * 获取规则详细信息
     */
    //@PreAuthorize("@ss.hasPermi('drools:rule:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id)
    {
        return success(ruleService.queryById(id));
    }

    /**
     * 新增规则
     */
    @ApiOperation("新增规则")
    //@PreAuthorize("@ss.hasPermi('drools:rule:add')")
    @Log(title = "规则", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody  RuleBo ruleBo)
    {
        return toAjax(ruleService.insertByBo(ruleBo));
    }

    /**
     * 修改规则
     */
    @ApiOperation("修改规则")
    //@PreAuthorize("@ss.hasPermi('drools:rule:edit')")
    @Log(title = "规则", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RuleBo ruleBo)
    {
        return toAjax(ruleService.updateByBo(ruleBo));
    }

    /**
     * 删除规则
     */
    @ApiOperation("删除规则")
    //@PreAuthorize("@ss.hasPermi('drools:rule:remove')")
    @Log(title = "规则", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids)
    {
        return toAjax(ruleService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    @ApiOperation("刷新规则")
    @GetMapping("/reload")
    public AjaxResult reload() {
        ruleEngineService.reload();
        return success(true);
    }

    @ApiOperation("运行规则")
    @PostMapping("fire")
    public AjaxResult fireAllRules(@RequestBody Map<String,Object> params) {
        KieSession kSession = ruleEngineService.getKieContainer().newKieSession();
        if(Objects.isNull(params)){
            params = new HashMap<String,Object>();
        }
        RuleFact result = new RuleFact();
        result.setMap(params);
        try {
            kSession.insert(result);
            kSession.fireAllRules();
        } finally {
            kSession.dispose();
        }
        return success(result.getResult());
    }

}
